package com.taptech.doufu.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.adapter.CpOrderListAdapter;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.bean.cp.CpBean;
import com.taptech.doufu.services.CpService;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.PullToRefreshListView;
import com.taptech.doufu.ui.view.PullToRefreshListView.OnScrollToBottomListener;
import com.taptech.doufu.ui.view.WaitDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class CpSearchActivity extends DiaobaoBaseActivity implements HttpResponseListener, View.OnClickListener {

    protected PullToRefreshListView mSweepListView;
    protected CpOrderListAdapter listViewAdapter;
    // http请求中
    protected String last = "";
    protected boolean hasMoreContent = true;
    protected WaitDialog dialog;
    protected ImageView mFragmentLayout, clean_iv;
    public static Handler handler;
    int position;
    private boolean isLoading = false;
    private List<CpBean> mainList = new ArrayList<CpBean>();
    private EditText search_et;
    private TextView search_tv;
    private ImageView tool_back_iv;
    private int type;
    private TextView show_tv;
    private Button add_cp;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addShadeBg();
        setContentView(R.layout.activity_cp_search);
        initView();
        loadLatestData();
    }


    protected void initView() {
        findID();
        dialog = new WaitDialog(CpSearchActivity.this, R.style.updateDialog, "搜索中,请稍后...");
        dialog.setCancelable(false);
        type = getIntent().getIntExtra(Constant.TYPE, -1);
        handler = new Handler() {
            public void handleMessage(Message msg) {
                position = msg.arg1;
                String cp_id = "";
                if (mainList != null && mainList.size() > position && mainList.get(position) != null) {
                    cp_id = ((CpBean) mainList.get(position)).getId();
                }
                switch (msg.what) {
                    case 1:
                        CpService.getInstance().addCp(cp_id, CpSearchActivity.this);
                        CpService.getInstance().recordSearchCp(CpSearchActivity.this, search_et.getText().toString().trim(), mainList.get(position).getName());
                        break;
                    case 2:
                        CpService.getInstance().cancelCp(cp_id, CpSearchActivity.this);
                        break;
                    case 3:
                        TTLog.i("TAG", "handleMessage:" + msg.what);
                        listViewAdapter.notifyDataSetChanged();
                        break;
                    default:
                        break;
                }
            }
        };
        listViewAdapter = new CpOrderListAdapter(CpSearchActivity.this, mainList, handler);
        mFragmentLayout = (ImageView) findViewById(R.id.fragment_background_id);
        mSweepListView = (PullToRefreshListView) findViewById(R.id.sweep_fragment_listview);
        mSweepListView.setRefreshable(false);
        mSweepListView.setLoadmoreable(true);

        mSweepListView.setOnScrollToBottomListener(new OnScrollToBottomListener() {

            @Override
            public void OnScrollToBottom() {

                //mSweepListView.loadMore();
                loadMoreData();


            }
        });
        mSweepListView.setAdapter(listViewAdapter);
        mSweepListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(CpSearchActivity.this, NewCpDesActivity.class);
                int position = Integer.parseInt(Long.toString(l));
                CpBean data = (CpBean) mainList.get(position);
                intent.putExtra(Constant.TOPIC_ID, data.getId());
                intent.putExtra(Constant.TYPE, NewCpDesActivity.TYPE_CP);
                startActivityForResult(intent, Constant.TAG_ADD_FROM_UGC);

            }
        });
        // 获取数据并显示专题图
        //showAlbums(topAlbumsList);
    }

    private void findID() {
        add_cp = (Button) findViewById(R.id.add_cp);
        search_et = (EditText) findViewById(R.id.search_et);
        search_tv = (TextView) findViewById(R.id.search_tv);
        clean_iv = (ImageView) findViewById(R.id.clean_iv);
        show_tv = (TextView) findViewById(R.id.show_tv);
        tool_back_iv = (ImageView) findViewById(R.id.tool_back_iv);
        add_cp.setOnClickListener(this);
        tool_back_iv.setOnClickListener(this);
        search_tv.setOnClickListener(this);
        clean_iv.setOnClickListener(this);
        search_et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (search_et.getText().toString().trim().length() > 0) {
                    clean_iv.setVisibility(View.VISIBLE);
                } else {
                    clean_iv.setVisibility(View.INVISIBLE);
                    show_tv.setVisibility(View.VISIBLE);
                    reSetList();
                }
            }
        });

    }

    private void reSetList() {
        mainList.clear();
        if (tempList != null && tempList.size() > 0) {
            mainList.addAll(tempList);
        }
        listViewAdapter.notifyDataSetChanged();
    }

    private List<CpBean> tempList;

    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        try {
            UIUtil.dismissDialog();
            switch (handleType) {
                case CpService.HANDLE_LOAD_HOT_CPS:
                    isLoading = false;
                    if (response.getStatus() == Constant.STATUS_SUCCESS) {
                        JSONObject data = (JSONObject) response.getData();
                        tempList = DiaobaoUtil.json2list(CpBean.class, data.getJSONArray("cps"));
                        mSweepListView.setFull(true);
                        if (last.equals("")) {
                            mainList.clear();
                        }
                        if (tempList != null) {
                            mainList.addAll(tempList);
                        }
                        listViewAdapter.notifyDataSetChanged();
                        TTLog.i("TAG", "setData:" + "111");
                        mSweepListView.loadMoreComplete();

                    } else {
                        UIUtil.toastMessage(CpSearchActivity.this, DiaobaoUtil.getErrorTips(response));
                    }
                    break;
                case CpService.HANDLE_LOAD_SEARCH_CPS:
                    show_tv.setVisibility(View.GONE);
                    dialog.dismiss();
                    if (response.getStatus() == Constant.STATUS_SUCCESS) {
                        JSONObject data = (JSONObject) response.getData();
                        List<CpBean> tempList = DiaobaoUtil.json2list(CpBean.class, data.getJSONArray("cps"));
                        if (tempList != null && tempList.size() > 0) {
                            if (last.equals("")) {
                                mainList.clear();
                                mainList.addAll(tempList);
                                mSweepListView.setFull(false);
                                mSweepListView.setLoadmoreable(true);
                            } else if (!last.equals(data.getString("last"))) {
                                if (tempList.size() > 0) {
                                    mainList.addAll(tempList);
                                }
                                mSweepListView.setFull(false);
                                mSweepListView.loadMoreComplete();
                                mSweepListView.setLoadmoreable(true);
                                hasMoreContent = true;
                            }
                        } else {
                            mSweepListView.setFull(true);
                            mSweepListView.loadMoreComplete();
                            mSweepListView.setLoadmoreable(false);
                            hasMoreContent = false;
                        }
                        last = data.getString("last");
                        listViewAdapter.notifyDataSetChanged();

                    } else {
                        UIUtil.toastMessage(CpSearchActivity.this, DiaobaoUtil.getErrorTips(response));
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public void onDestroy() {
        mainList.clear();
        super.onDestroy();

    }

    protected synchronized void loadLatestData() {
        last = "";
        isLoading = true;
        CpService.getInstance().loadHotCps(this);
    }

    /**
     * 上 加
     */
    protected synchronized void loadMoreData() {
        if (hasMoreContent) {
            hasMoreContent = false;
            isLoading = true;
            if (search_et.getText().toString().trim().length() > 0) {
                CpService.getInstance().searchCps(search_et.getText().toString().trim(), last, this);
            } else {
                CpService.getInstance().loadHotCps(this);
            }

        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tool_back_iv:
                backWithdata();
                //finish();
                break;
            case R.id.clean_iv:
                search_et.setText("");
                break;
            case R.id.search_tv:
                ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(CpSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                if (search_et.getText().toString() != null && search_et.getText().toString().length() > 0) {
                    dialog.show();
                    loadSearchData();
                } else {
                    Toast.makeText(CpSearchActivity.this, "您还没有输入搜索内容噢！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.add_cp:
                Intent intent = new Intent(this.getApplicationContext(), BrowseActivity.class);
                intent.putExtra(Constant.URL, "http://api.doufu.la/web/src/requests/cps/index.html");
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void backWithdata() {
        Intent intent = new Intent();
        intent.putExtra(Constant.TYPE, type);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void loadSearchData() {
        last = "";
        isLoading = true;
        hasMoreContent = true;
        mainList.clear();
        // mSweepListView.setFull(false);
        // mSweepListView.loadMoreNoComplete();
        //UIUtil.showProgressDialog(CpSearchActivity.this);
        CpService.getInstance().searchCps(search_et.getText().toString().trim(), last, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (search_et.getText().toString().trim().length() > 0) {
                loadSearchData();
            } else {
                loadLatestData();
            }
        }
    }

    public static Handler getHandler() {
        return handler;
    }
}